<template>
  <div class="calendar-page">
    <el-container>
      <el-header class="header">
        <div class="header-content">
          <div class="header-left">
            <el-button @click="$router.push('/dashboard')" icon="ArrowLeft" class="back-btn">
              返回
            </el-button>
          </div>
          <div class="header-center">
            <div class="page-title">
              <el-icon class="title-icon"><Calendar /></el-icon>
              <h2>日历</h2>
            </div>
          </div>
          <div class="header-right">
            <div class="calendar-controls">
              <el-button @click="previousMonth" icon="ArrowLeft" class="nav-btn">上月</el-button>
              <div class="current-month">
                <span class="month-text">{{ currentYear }}.{{ currentMonth }}.{{ currentDay }}</span>
                <span class="week-text">周{{ currentWeekDay }}</span>
              </div>
              <el-button @click="nextMonth" icon="ArrowRight" class="nav-btn">下月</el-button>
            </div>
          </div>
        </div>
      </el-header>
      
      <!-- 可编辑标题 -->
      <div class="editable-title-container">
        <div 
          class="editable-title" 
          @dblclick="startEditTitle"
          v-if="!isEditingTitle"
        >
          {{ pageTitle }}
        </div>
        <el-input
          v-if="isEditingTitle"
          v-model="editingTitle"
          @blur="saveTitle"
          @keyup.enter="saveTitle"
          @keyup.escape="cancelEditTitle"
          ref="titleInput"
          class="title-input"
          size="large"
        />
      </div>
      
      <el-main class="main">
        <el-card class="calendar-card">
          <div class="calendar-header">
            <div class="weekday" v-for="day in weekdays" :key="day">{{ day }}</div>
          </div>
          
          <div class="calendar-body">
            <div 
              v-for="day in calendarDays" 
              :key="day.date"
              class="calendar-day"
              :class="{
                'other-month': !day.isCurrentMonth,
                'today': day.isToday,
                'has-records': day.hasRecords,
              }"
              @click="handleDayDoubleClick(day)"
            >
               <!-- 仅当月日期显示数字和记录标记 -->
              <div class="day-number" v-if="day.isCurrentMonth"> {{ day.dayNumber }} <span v-if="day.hasDiary">...</span>
              </div>
              <div v-if="day.hasRecords" class="day-info">
                <div class="time-info">{{ formatTime1(day.totalTime) }}</div>
              </div>
            </div>
          </div>
        </el-card>
        
        <!-- 当月计时记录 -->
        <el-card class="monthly-timer-card" v-if="monthlyTimerData.hasRecords">
          <template #header>
            <div class="monthly-timer-header">
              <h3>当月计时记录</h3>
              <el-tag type="success">{{ currentYear }}年{{ currentMonth }}月</el-tag>
            </div>
          </template>
          
          <div class="monthly-timer-content">
            <div class="timer-summary">
              <div class="summary-item">
                <div class="summary-label">总计时时间</div>
                <div class="summary-value">{{ formatTime(monthlyTimerData.totalTime) }}</div>
              </div>
              <div class="summary-item">
                <div class="summary-label">倒计时</div>
                <div class="summary-value">{{ formatTime(monthlyTimerData.countdownTime) }}</div>
              </div>
              <div class="summary-item">
                <div class="summary-label">正计时</div>
                <div class="summary-value">{{ formatTime(monthlyTimerData.timerTime) }}</div>
              </div>
              <div class="summary-item">
                <div class="summary-label">有记录天数</div>
                <div class="summary-value">{{ monthlyTimerData.recordDays }}天</div>
              </div>
            </div>
            
            <div class="timer-chart" v-if="monthlyTimerData.dailyStats.length > 0">
              <h4>每日计时统计</h4>
              <div class="chart-container">
                <div 
                  v-for="(stat, index) in monthlyTimerData.dailyStats" 
                  :key="index"
                  class="chart-bar"
                  :style="{ height: getBarHeight(stat.totalTime) + 'px' }"
                  :title="`${stat.date}: ${formatTime(stat.totalTime)}`"
                >
                  <div class="bar-label">{{ stat.day }}</div>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-main>
    </el-container>
    
    <!-- 悬浮主题切换按钮 -->

  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
// import axios from 'axios'
// 新写法（自动适配环境）
import request from '../utils/request'
import dayjs from 'dayjs'


const router = useRouter()
const currentDate = ref(new Date())
const calendarData = ref({})
const monthlyTimerData = ref({
  hasRecords: false,
  totalTime: 0,
  countdownTime: 0,
  timerTime: 0,
  recordDays: 0,
  dailyStats: []
})

// 可编辑标题相关
const pageTitle = ref('天天upup')
const isEditingTitle = ref(false)
const editingTitle = ref('')
const titleInput = ref(null)

const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']

const currentYear = computed(() => currentDate.value.getFullYear())
const currentMonth = computed(() => currentDate.value.getMonth() + 1)
const currentDay = computed(() => currentDate.value.getDate())
const currentWeekDay = computed(() => {
  const weekDays = ['日', '一', '二', '三', '四', '五', '六']
  return weekDays[currentDate.value.getDay()]
})

const calendarDays = computed(() => {
  const year = currentYear.value
  const month = currentMonth.value
  const firstDay = new Date(year, month - 1, 1)
  const lastDay = new Date(year, month, 0)
  const startDate = new Date(firstDay)
  startDate.setDate(startDate.getDate() - firstDay.getDay())
  
  const days = []
  const today = new Date()
  
  for (let i = 0; i < 42; i++) {
    const date = new Date(startDate)
    date.setDate(startDate.getDate() + i)
    
    const dateString = dayjs(date).format('YYYY-MM-DD')
    const dayData = calendarData.value[dateString] || {}
    
    days.push({
      date: dateString,
      dayNumber: date.getDate(),
      isCurrentMonth: date.getMonth() === month - 1,
      isToday: dayjs(date).isSame(today, 'day'),
      hasRecords: dayData.hasTimerRecords,
      hasDiary: dayData.hasDiary,
      totalTime: dayData.totalTime || 0
    })
  }
  
  return days
})

const formatTime = (seconds) => {
  if (!seconds) return '0小时0分钟'
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  return `${hours}小时${minutes}分钟`
}
const formatTime1 = (seconds) => {
  if (!seconds) return ''
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  if (hours > 0) {
    return `${hours}h${minutes > 0 ? minutes + 'm' : ''}`
  }
  return `${minutes}m`
}

const getBarHeight = (totalTime) => {
  if (!totalTime) return 10
  const maxTime = Math.max(...monthlyTimerData.value.dailyStats.map(stat => stat.totalTime))
  if (maxTime === 0) return 10
  return Math.max(10, (totalTime / maxTime) * 100)
}

const previousMonth = () => {
  currentDate.value = new Date(currentYear.value, currentMonth.value - 2, 1)
  loadCalendarData()
  loadMonthlyTimerData()
}

const nextMonth = () => {
  currentDate.value = new Date(currentYear.value, currentMonth.value, 1)
  loadCalendarData()
  loadMonthlyTimerData()
}

const loadCalendarData = async () => {
  try {
    const year = currentYear.value
    const month = currentMonth.value.toString().padStart(2, '0')
    const response = await  request.get(`/calendar/${year}/${month}`)
    calendarData.value = response.data.calendarData
  } catch (error) {
    console.error('加载日历数据失败:', error)
  }
}

const loadMonthlyTimerData = async () => {
  try {
    const year = currentYear.value
    const month = currentMonth.value.toString().padStart(2, '0')
    const response = await  request.get(`/timer/monthly/${year}/${month}`)
    monthlyTimerData.value = response.data
  } catch (error) {
    console.error('加载月度计时数据失败:', error)
  }
}

const handleDayDoubleClick = (day) => {
  if (day.isCurrentMonth) {
    router.push(`/diary/${day.date}`)
  }
}

// 标题编辑相关方法
const startEditTitle = () => {
  isEditingTitle.value = true
  editingTitle.value = pageTitle.value
  nextTick(() => {
    titleInput.value?.focus()
    titleInput.value?.select()
  })
}

const saveTitle = () => {
  if (editingTitle.value.trim()) {
    pageTitle.value = editingTitle.value.trim()
    localStorage.setItem('calendarPageTitle', pageTitle.value)
  }
  isEditingTitle.value = false
}

const cancelEditTitle = () => {
  isEditingTitle.value = false
  editingTitle.value = ''
}

// 从localStorage加载标题
const loadPageTitle = () => {
  const savedTitle = localStorage.getItem('calendarPageTitle')
  if (savedTitle) {
    pageTitle.value = savedTitle
  }
}

onMounted(() => {
  loadPageTitle()
  loadCalendarData()
  loadMonthlyTimerData()
})
</script>

<style scoped>
  /* 穿透 scoped 作用域，定位 el-card__body */
::v-deep .el-card__body {
  /* 添加背景图（替换为你的图片路径） */
  background-image: url('/public/assets/daymode.jpeg'); /* 项目内图片 */
  /* 或网络图片：background-image: url('https://example.com/bg.jpg'); */
   /* 背景图适配核心样式（确保图片显示正常） */
  background-size: cover; /* 图片覆盖整个卡片内容区，优先保证填满 */
 
  min-height: 200px; /* 可选：设置最小高度，避免卡片过矮时背景图显示不全 */
  
  /* 相对定位：为后续加遮罩做准备（提升文字可读性） */
  position: relative;

  padding: 1px;

}

.dark-theme .el-main {
  background: var(--header-bg);
}
.dark-theme .editable-title-container
 {
  background: var(--header-bg);
}
.dark-theme .weekday{
   background: gray;
}
.dark-theme .summary-item {
   background: rgb(69, 68, 68);
}
.dark-theme .calendar-page {
  background: var(--header-bg);
}
/* 2. 可选：添加半透明遮罩（防止文字与背景图颜色冲突） */
::v-deep .el-card__body::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  /* 白色半透明遮罩（透明度 0.6，可根据图片亮度调整） */
  background-color: rgba(255, 255, 255, 0.3);
  z-index: 0; /* 遮罩在背景图之上，文字之下 */
}

/* 3. 确保卡片内的内容（如日历、文字）在最上层 */
::v-deep .el-card__body > * {
  position: relative;
  z-index: 1;
}

.calendar-page {
  min-height: 100vh;
  background-color: var(--bg-primary);
}

.header {
  background: var(--header-bg);
  color: white;
  padding: 0 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  position: relative;
}

.header-left {
  display: flex;
  align-items: center;
}

.header-center {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  align-items: center;
}

.header-right {
  display: flex;
  align-items: center;
}

.page-title {
  display: flex;
  align-items: center;
  gap: 12px;
  background: rgba(255, 255, 255, 0.1);
  padding: 8px 16px;
  border-radius: 12px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.title-icon {
  font-size: 24px;
  color: #ffd700;
  filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.2));
}

.page-title h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: white;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.back-btn {
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: white;
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
  border-radius: 8px;
  font-weight: 500;
}

.back-btn:hover {
  background: rgba(255, 255, 255, 0.2);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.calendar-controls {
  display: flex;
  align-items: center;
  gap: 12px;
  background: rgba(255, 255, 255, 0.1);
  padding: 8px 16px;
  border-radius: 12px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.nav-btn {
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: white;
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
  border-radius: 6px;
  font-weight: 500;
  min-width: 60px;
}

.nav-btn:hover {
  background: rgba(255, 255, 255, 0.2);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.current-month {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2px;
  min-width: 120px;
  text-align: center;
}

.month-text {
  font-size: 16px;
  font-weight: 600;
  color: white;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
}

.week-text {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.8);
  font-weight: 500;
}

/* 可编辑标题样式 */
.editable-title-container {
  padding: 10px 20px 0 20px;
  text-align: center;
}

.editable-title {
  font-size: 15px;
  font-weight: 510;
  color: var(--text-primary);
  cursor: pointer;
  padding: 5px 14px;
  border-radius: 12px;
  transition: all 0.3s ease;
    /* background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); */
  background: white;
  color: #0f1114;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
  display: inline-block;
  min-width: 200px;
}

.editable-title:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

.title-input {
  max-width: 300px;
  margin: 0 auto;
}

.title-input ::v-deep .el-input__wrapper {
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
  border: 2px solid #667eea;
}

.title-input ::v-deep .el-input__inner {
  text-align: center;
  font-size: 24px;
  font-weight: 700;
  color: #667eea;
}

.main {
  padding: 10px;
}

.calendar-card {
  max-width: 800px;
  margin: 0 auto 20px;
  background-color: var(--bg-card);
  border-color: var(--border-color);
}

.calendar-header {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 1px ;

   /* border: 2px solid yellow; */
   /* 只设置左、右、上边框，去掉下边框 */
  border-left: 1px solid ;
  border-right: 1px solid ;
   border-top: 1px solid; 
  border-bottom: none ; /* 关键：去掉下边框 */
  /* 可选：外边框圆角 */
  /* border-radius: 4px;  */
  overflow: hidden; /* 避免内部网格项的边框超出容器 */

  background-color: var(--border-color);
  border-bottom: 1px solid var(--border-color);
}

.weekday {
  padding: 12px;
  text-align: center;
  font-weight: 600;
  background-color: var(--bg-card);
  /* color: var(--text-secondary); */
  color:  #060606;
}

.calendar-body {

  display: grid;  /* 网格容器布局 */
  grid-template-columns: repeat(7, 1fr);
  /* gap: 1px; */
  
  /* 只设置左、右、下边框，去掉上边框 */
  border-left: 1px solid ;
  border-right: 1px solid ;
   border-top: none; /* 关键：去掉上边框 */
  border-bottom: 1px solid ; 
  /* 可选：外边框圆角 */
  /* border-radius: 4px;  */
  overflow: hidden; /* 避免内部网格项的边框超出容器 */

  /* background-color: var(--border-color); */
  background-color: transparent !important; /* 强制设置为透明，!important 确保优先级 */
}

.calendar-day {
  min-height: 80px;
  /* background-color: var(--bg-card); */
  background-color: transparent !important; /* 强制设置为透明，!important 确保优先级 */
  padding: 8px;
  cursor: pointer;
  transition: background-color 0.2s;
  display: flex;
  flex-direction: column; /* 子元素垂直排列（日期在上，计时在下） */
  justify-content: center; /* 垂直方向居中 */
  align-items: center; /* 水平方向居中 */
  
  border: 1px solid grey; /* 浅灰色边框，模拟网格线 */
   /* 日期和计时信息之间的间距，可按需调整 */
  gap: 4px; 
}

.calendar-day:hover {
  background-color: var(--hover-bg);
}

.calendar-day.other-month {
  color: var(--text-muted);
}

.calendar-day.today .day-number {
  /* 删掉/注释掉原有的背景、边框样式（若不需要），保留或新增文字颜色 */
  /* background-color: var(--today-bg);
  border: 2px solid var(--today-border); */
  color: red !important; /* 新增：控制格子内所有默认文字颜色为红色 */
   /* 也可以不加 !important，靠选择器具体性（.calendar-day.today .day-number 比 .day-number 更具体）自然覆盖 */
  /* color: red; */
}

.calendar-day.has-records {
  background-color: var(--records-bg);
}

.day-number {
  font-size: 16px;
  font-weight: 600;
  text-align: center;
  margin-bottom: 4px;
  /* color: var(--text-primary); */
  color: #0f1114;
}

.day-info {
  text-align: center;
  font-size: 12px;
}

.time-info {
  color: #52c41a;
  font-weight: 600;
}

/* 月度计时记录样式 */
.monthly-timer-card {
  max-width: 800px;
  margin: 0 auto;
  background-color: var(--bg-card);
  border-color: var(--border-color);
}

.monthly-timer-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.monthly-timer-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: var(--text-primary);
}

.monthly-timer-content {
  padding: 16px 0;
}

.timer-summary {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  margin-bottom: 24px;
}

.summary-item {
  text-align: center;
  padding: 16px;
  background-color: var(--bg-primary);
  border-radius: 8px;
  border: 1px solid var(--border-color);
}

.summary-label {
  font-size: 14px;
  color: var(--text-secondary);
  margin-bottom: 8px;
}

.summary-value {
  font-size: 20px;
  font-weight: 600;
  color: var(--text-primary);
}

.timer-chart {
  margin-top: 24px;
}

.timer-chart h4 {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
}

.chart-container {
  display: flex;
  align-items: end;
  gap: 4px;
  height: 120px;
  padding: 16px 0;
  border-bottom: 1px solid var(--border-color);
}

.chart-bar {
  flex: 1;
  background: linear-gradient(to top, #409eff, #67c23a);
  border-radius: 4px 4px 0 0;
  min-width: 20px;
  position: relative;
  transition: all 0.3s ease;
}

.chart-bar:hover {
  background: linear-gradient(to top, #1890ff, #52c41a);
  transform: scaleY(1.05);
}

.bar-label {
  position: absolute;
  bottom: -20px;
  left: 50%;
  transform: translateX(-50%);
  font-size: 10px;
  color: var(--text-secondary);
  white-space: nowrap;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .editable-title-container {
    padding: 15px 15px 0 15px;
  }
  
  .editable-title {
    font-size: 22px;
    padding: 1px 20px;
    min-width: 190px;
  }
  
  .title-input {
    max-width: 250px;
  }
  
  .title-input ::v-deep .el-input__inner {
    font-size: 20px;
  }
  
  html.app-5plus .header {
    padding-top: var(--status-bar-height);
    height: calc(55px + var(--status-bar-height));
  }
  
  .header-content {
    flex-direction: row;
    padding: 10px 0;
    gap: 6px;
  }
  
  .page-title {
    padding: 6px 12px;
    gap: 8px;
  }
  
  .title-icon {
    font-size: 20px;
  }
  
  .page-title h2 {
    font-size: 16px;
  }
  
  .back-btn {
    padding: 6px 10px;
    font-size: 14px;
  }
  
  .calendar-controls {
    padding: 6px 12px;
    gap: 8px;
  }
  
  .nav-btn {
    min-width: 50px;
    font-size: 12px;
    padding: 4px 8px;
  }
  
  .current-month {
    min-width: 100px;
  }
  
  .month-text {
    font-size: 14px;
  }
  
  .week-text {
    font-size: 10px;
  }
  .header-content {
    flex-direction: row; 
    padding: 10px 0;
    gap: 6px;
    
  }

  .header-content .el-button span {
    display: none;
  }
  
  .current-month {
    font-size: 14px;
    min-width: auto;
    white-space: nowrap;
  }

  .header-content .el-button {
    padding: 6px 12px;
    font-size: 13px;
  }
  
  .main {
    padding: 10px;
  }
  
  .calendar-day {
    min-height: 60px;
    padding: 4px;
  }
  
  .day-number {
    font-size: 16px;
  }
  
  .day-info {
    font-size: 10px;
  }
  
  .timer-summary {
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
  }
  
  .summary-item {
    padding: 12px;
  }
  
  .summary-value {
    font-size: 16px;
  }
  
  .chart-container {
    height: 100px;
    gap: 2px;
  }
  
  .chart-bar {
    min-width: 16px;
  }
  
  .bar-label {
    font-size: 8px;
  }
}
</style> 